<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdateDepartmentRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        // 获取当前部门（路由参数可能是模型实例或 ID）
        $department = $this->route('department');
        $departmentId = null;
        $currentParentId = 0;
        
        if ($department instanceof \App\Models\Department) {
            $departmentId = $department->id;
            $currentParentId = $department->parent_id ?? 0;
        } else {
            // 如果是 ID，从路由获取
            $departmentId = $department ?? $this->route('id');
            if ($departmentId) {
                $dept = \App\Models\Department::find($departmentId);
                if ($dept) {
                    $currentParentId = $dept->parent_id ?? 0;
                }
            }
        }
        
        // 如果请求中没有提供 parent_id，使用当前部门的 parent_id
        if (!$this->has('parent_id') && $departmentId) {
            $this->merge([
                'parent_id' => $currentParentId,
            ]);
        }
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        // 获取部门 ID
        $department = $this->route('department');
        $departmentId = $department instanceof \App\Models\Department 
            ? $department->id 
            : ($department ?? $this->route('id'));
        
        // 获取 parent_id（prepareForValidation 已确保有值）
        $parentId = $this->input('parent_id', 0);
        
        return [
            'parent_id' => 'nullable|exists:departments,id|not_in:' . $departmentId,
            'name' => [
                'required',
                'string',
                'max:255',
                Rule::unique('departments', 'name')
                    ->where(function ($query) use ($parentId) {
                        return $query->where('parent_id', $parentId);
                    })
                    ->ignore($departmentId),
            ],
            'code' => 'nullable|string|unique:departments,code,' . $departmentId,
            'leader' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'status' => 'required|integer|in:' . implode(',', [
                \App\Models\Department::STATUS_DISABLED,
                \App\Models\Department::STATUS_ENABLED,
            ]),
            'sort' => 'nullable|integer',
            'remark' => 'nullable|string',
        ];
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array
     */
    public function messages(): array
    {
        return [
            'name.required' => '部门名称不能为空',
            'name.unique' => '同级部门名称不能重复',
            'code.unique' => '部门编码已存在',
            'email.email' => '邮箱格式不正确',
            'status.required' => '状态不能为空',
            'status.in' => '状态值不正确',
            'parent_id.exists' => '父部门不存在',
            'parent_id.not_in' => '不能选择自己作为父部门',
        ];
    }
}

